package global

import (
	"seat-service/initialization"
	"seat-service/model"
)

//对于字典，需要一个map去存储键值对。需要持久化到sql里，
//第一步创建两个sql表  √
//第二步创建一个字典，创建一个map，读取数据库中的记录进行录入 √
//第三步维护这个字典，提供增删改查功能 √

var dic map[uint]model.DictionaryMS

func init() {
	dic = make(map[uint]model.DictionaryMS)
}

// LoadDic 从持久层加载字典数据
func LoadDic() {
	dicSlice := make([]model.Dictionary, 0)
	dicSlaveSlice := make([]model.DictionarySlave, 0)
	var err error
	err = initialization.DB.Model(&model.Dictionary{}).Find(&dicSlice).Error
	err = initialization.DB.Model(&model.DictionarySlave{}).Find(&dicSlaveSlice).Error
	if err != nil {
		initialization.SeatLogger.Error("字典异常，加载失败")
		panic("字典异常，加载失败")
	}
	for _, v := range dicSlice {
		dicMS := model.DictionaryMS{}
		dicMS.Master = v
		res := make(map[uint]model.DictionarySlave)
		for _, v2 := range dicSlaveSlice {
			if v.ID == v2.DictionaryId {
				res[uint(v2.Value)] = v2
			}
		}
		dicMS.Slave = res
		dic[v.ID] = dicMS
	}
	initialization.SeatLogger.Info("字典初始化成功")
}

/*
添加dic Master数据
传入Dictionary结构体,需要携带id
*/

func AddDictionaryMaster(dictionary model.Dictionary) {
	dic[dictionary.ID] = model.DictionaryMS{
		Master: dictionary,
		Slave:  make(map[uint]model.DictionarySlave),
	}
}

/*
添加dic Slave数据
传入DictionarySlave结构体,需要携带id
*/

func AddDictionarySlave(slave model.DictionarySlave) {
	//获取到MS结构体,此时master是有数据的，slave有两种情况 nil 或 存在数据
	d := dic[slave.DictionaryId]
	if d.Slave == nil {
		slaveMap := make(map[uint]model.DictionarySlave)
		slaveMap[slave.ID] = slave
		d.Slave = slaveMap
	} else {
		d.Slave[slave.ID] = slave
	}
}

/*
删除dic Master数据
*/

func DeleteDictionaryMaster(masterId uint) {
	delete(dic, masterId)
}

/*
删除dic Slave数据
传入DictionarySlave结构体,需要携带id
*/

func DeleteDictionarySlave(slaveID, masterID uint) {
	d := dic[masterID].Slave
	delete(d, slaveID)
}

/*
修改dic Master数据
传入DictionarySlave结构体,需要携带id
*/

func UpdateDictionaryMaster(dictionary model.Dictionary) {
	d := dic[dictionary.ID]
	d.Master = dictionary
}

/*
修改dic Slave数据
传入DictionarySlave结构体,需要携带id
*/

func UpdateDictionarySlave(slave model.DictionarySlave) {
	d := dic[slave.DictionaryId]
	s := d.Slave
	s[slave.ID] = slave
}

/*
查找全部dic Master数据
*/

func QueryAllDictionaryMaster() (master []model.Dictionary) {
	for _, v := range dic {
		master = append(master, v.Master)
	}
	return
}

/*
查找全部dic Slave数据
传入master id
*/

func QueryAllDictionarySlave(masterId uint) (slave []model.DictionarySlave) {
	d := dic[masterId].Slave
	for _, v := range d {
		slave = append(slave, v)
	}
	return
}

/*
查找单个dic Master数据
传入master id
*/

func QueryOneDictionaryMaster(masterId uint) model.Dictionary {

	return dic[masterId].Master
}

/*
查找单个dic Slave数据
传入master和salve id
*/

func QueryOneDictionarySlave(masterId, slaveId uint) model.DictionarySlave {
	d := dic[masterId].Slave
	return d[slaveId]
}

func ObtainDic() map[uint]model.DictionaryMS {
	return dic
}
